package 链表.移除链表元素;

/**
 * @author: wh(1835734390 @ qq.com)
 * @date: 2023/2/3 13:40
 * @description:
 * @version:
 */
public class Solution {
    public static void main(String[] args) {
        ListNode root = new ListNode(2,new ListNode(2,new ListNode(2,new ListNode(2))));
        System.out.println(removeElements2(root, 2).val);
    }

    //官方解法
    public static ListNode removeElements(ListNode head, int val) {
        ListNode dummyHead = new ListNode(0);
        dummyHead.next = head;
        ListNode temp = dummyHead;
        while (temp.next != null) {
            if (temp.next.val == val) {
                temp.next = temp.next.next;
            } else {
                temp = temp.next;
            }
        }
        return dummyHead.next;
    }


    public static ListNode removeElements2(ListNode head, int val) {
        //定义头节点
        ListNode root = new ListNode(-1);
        root.next = head;
        ListNode pre = root;
        ListNode p = root.next;
        while (p != null){
            if (p.val == val){
                pre.next = p.next;
                //这一步必不可少
                p = pre.next;
            }else{
                pre = p;
                p = p.next;
            }
        }
        return root.next;
    }

}
